// GameDataService.ts
import { _decorator, Component } from 'cc';
import { GameData, PlayerInfo, EquipmentItem, MountItem, PetItem, InventoryItem } from './GameDataModels';

const { ccclass } = _decorator;

@ccclass('GameDataService')
export class GameDataService extends Component {
    private static instance: GameDataService | null = null;
    private gameData: GameData;

    public static getInstance(): GameDataService {
        if (!GameDataService.instance) {
            GameDataService.instance = new GameDataService();
            GameDataService.instance.init();
        }
        return GameDataService.instance;
    }

    // constructor() {
    //     super();
    //     this.loadData();
    // }

    private init() {
        this.loadData();
    }

    // 初始化模拟数据
    private createMockData(): GameData {
        return {
            player: {
                id: "player_001",
                name: "冒险者",
                level: 15,
                exp: 2500,
                gold: 12500,
                diamond: 150,
                power: 3780,
                avatar: "avatar_001",
                title: "骑士"
            },
            equipment: {
                weapon: {
                    id: "equip_1001",
                    type: "weapon",
                    name: "烈焰长剑",
                    rarity: "rare",
                    level: 12,
                    attack: 145,
                    defense: 20,
                    durability: 85,
                    equipped: true
                },
                armor: {
                    id: "equip_2001",
                    type: "armor",
                    name: "精钢铠甲",
                    rarity: "uncommon",
                    level: 10,
                    attack: 0,
                    defense: 88,
                    durability: 92,
                    equipped: true
                },
                pants: {
                    id: "equip_3001",
                    type: "pants",
                    name: "疾风长裤",
                    rarity: "uncommon",
                    level: 9,
                    attack: 0,
                    defense: 45,
                    durability: 78,
                    equipped: true
                },
                artifact: {
                    id: "equip_4001",
                    type: "artifact",
                    name: "守护护符",
                    rarity: "rare",
                    level: 11,
                    attack: 25,
                    defense: 35,
                    durability: 100,
                    equipped: true
                },
                mount: {
                    id: "mount_1001",
                    name: "闪电战马",
                    type: "horse",
                    level: 8,
                    exp: 1200,
                    speed: 15,
                    stamina: 180,
                    equipped: true
                }
            },
            inventory: [
                { id: "item_1001", type: "material", name: "铁矿石", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001a", type: "material", name: "铁矿石a", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001b", type: "material", name: "铁矿石b", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001c", type: "material", name: "铁矿石c", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001d", type: "material", name: "铁矿石d", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001e", type: "material", name: "铁矿石e", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001f", type: "material", name: "铁矿石f", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001g", type: "material", name: "铁矿石g", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001h", type: "material", name: "铁矿石h", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001i", type: "material", name: "铁矿石i", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001j", type: "material", name: "铁矿石j", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001a1", type: "material", name: "铁矿石a1", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001b1", type: "material", name: "铁矿石b1", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001c1", type: "material", name: "铁矿石c1", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001d1", type: "material", name: "铁矿石d1", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001e1", type: "material", name: "铁矿石e1", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001f1", type: "material", name: "铁矿石f1", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001g1", type: "material", name: "铁矿石g1", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001h1", type: "material", name: "铁矿石h1", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001i1", type: "material", name: "铁矿石i1", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001j1", type: "material", name: "铁矿石j1", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001a2", type: "material", name: "铁矿石a2", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001b2", type: "material", name: "铁矿石b2", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001c2", type: "material", name: "铁矿石c2", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001d2", type: "material", name: "铁矿石d2", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001e2", type: "material", name: "铁矿石e2", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001f2", type: "material", name: "铁矿石f2", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001g2", type: "material", name: "铁矿石g2", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001h2", type: "material", name: "铁矿石h2", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001i2", type: "material", name: "铁矿石i2", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001j2", type: "material", name: "铁矿石j2", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001a3", type: "material", name: "铁矿石a3", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001b3", type: "material", name: "铁矿石b3", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001c3", type: "material", name: "铁矿石c3", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001d3", type: "material", name: "铁矿石d3", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001e3", type: "material", name: "铁矿石e3", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001f3", type: "material", name: "铁矿石f3", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001g3", type: "material", name: "铁矿石g3", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001h3", type: "material", name: "铁矿石h3", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001i3", type: "material", name: "铁矿石i3", count: 25, maxStack: 99, value: 10 },
                { id: "item_1001j3", type: "material", name: "铁矿石j3", count: 25, maxStack: 99, value: 10 },
                { id: "item_1002", type: "consumable", name: "治疗药水", count: 12, maxStack: 20, value: 25 },
                { id: "item_1003", type: "material", name: "皮革", count: 18, maxStack: 99, value: 8 },
                { id: "equip_1002", type: "equipment", name: "寒冰法杖", count: 1, maxStack: 1, value: 350 },
                { id: "pet_1002", type: "pet", name: "精灵蛋", count: 1, maxStack: 1, value: 200 }
            ],
            pets: [
                {
                    id: "pet_1001",
                    name: "小火龙",
                    type: "fire",
                    level: 5,
                    exp: 800,
                    attack: 65,
                    defense: 40,
                    skills: ["火焰喷射", "抓击"],
                    state: "idle"
                }
            ],
            mounts: [
                {
                    id: "mount_1002",
                    name: "雷霆狮鹫",
                    type: "griffin",
                    level: 3,
                    exp: 300,
                    speed: 20,
                    stamina: 120,
                    equipped: false
                }
            ],
            lastUpdate: Date.now()
        };
    }

    // 加载数据
    private loadData() {
        try {
            const savedData = localStorage.getItem('game_save_data');
            if (savedData) {
                this.gameData = JSON.parse(savedData);
            } else {
                this.gameData = this.createMockData();
                this.saveData();
            }
        } catch (error) {
            console.error('加载数据失败:', error);
            this.gameData = this.createMockData();
        }
    }

    // 保存数据到本地
    private saveData() {
        try {
            this.gameData.lastUpdate = Date.now();
            localStorage.setItem('game_save_data', JSON.stringify(this.gameData));
        } catch (error) {
            console.error('保存数据失败:', error);
        }
    }

    // ============ 玩家数据操作 ============
    getPlayerInfo(): PlayerInfo {
        return { ...this.gameData.player };
    }

    updatePlayerInfo(updates: Partial<PlayerInfo>): void {
        this.gameData.player = { ...this.gameData.player, ...updates };
        this.saveData();
    }

    addGold(amount: number): void {
        this.gameData.player.gold += amount;
        this.saveData();
    }

    // ============ 装备数据操作 ============
    getEquipment(): any {
        return { ...this.gameData.equipment };
    }

    equipItem(itemId: string, slot: string): boolean {
        // 这里简化处理，实际应该检查物品是否存在等
        console.log(`装备物品: ${itemId} 到位置: ${slot}`);
        this.saveData();
        return true;
    }

    unequipItem(slot: string): boolean {
        this.gameData.equipment[slot] = null;
        this.saveData();
        return true;
    }

    // ============ 背包数据操作 ============
    getInventory(): InventoryItem[] {
        return [...this.gameData.inventory];
    }

    addToInventory(item: InventoryItem): boolean {
        const existingItem = this.gameData.inventory.find(i => i.id === item.id && i.count < i.maxStack);
        
        if (existingItem) {
            existingItem.count += item.count;
        } else {
            this.gameData.inventory.push(item);
        }
        
        this.saveData();
        return true;
    }

    removeFromInventory(itemId: string, count: number = 1): boolean {
        const itemIndex = this.gameData.inventory.findIndex(i => i.id === itemId);
        
        if (itemIndex === -1) return false;
        
        const item = this.gameData.inventory[itemIndex];
        item.count -= count;
        
        if (item.count <= 0) {
            this.gameData.inventory.splice(itemIndex, 1);
        }
        
        this.saveData();
        return true;
    }

    // ============ 宠物数据操作 ============
    getPets(): PetItem[] {
        return [...this.gameData.pets];
    }

    addPet(pet: PetItem): void {
        this.gameData.pets.push(pet);
        this.saveData();
    }

    // ============ 坐骑数据操作 ============
    getMounts(): MountItem[] {
        return [...this.gameData.mounts];
    }

    // ============ 后期替换为服务器接口的方法 ============
    /*
    // 从服务器加载数据
    async loadFromServer(): Promise<void> {
        try {
            const response = await fetch('/api/game/data', {
                headers: {
                    'Authorization': 'Bearer ' + getToken()
                }
            });
            if (response.ok) {
                this.gameData = await response.json();
            }
        } catch (error) {
            console.error('从服务器加载数据失败:', error);
        }
    }

    // 保存数据到服务器
    async saveToServer(): Promise<boolean> {
        try {
            const response = await fetch('/api/game/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + getToken()
                },
                body: JSON.stringify(this.gameData)
            });
            return response.ok;
        } catch (error) {
            console.error('保存数据到服务器失败:', error);
            return false;
        }
    }

    // 获取玩家信息（服务器版本）
    async getPlayerInfoFromServer(): Promise<PlayerInfo> {
        try {
            const response = await fetch('/api/player/info');
            return await response.json();
        } catch (error) {
            console.error('获取玩家信息失败:', error);
            throw error;
        }
    }
    */
}